import { View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { Button, Cell, NavBar } from 'react-vant'
import { ArrowLeft } from '@react-vant/icons'
import { useEffect, useState } from 'react'
import axios from 'axios'
import './index.less'
import { Provider, useDispatch } from 'react-redux'
import { selectAddress } from '@/store/addressSlice'
import { store } from '@/store'

interface AddressItem {
    _id: string;
    username: string;
    phone: string;
    address: string[];
    dAddress: string;
    isDefault: boolean;
}

const AddressContent = () => {
    const [addressList, setAddressList] = useState<AddressItem[]>([])
    const dispatch = useDispatch()

    const handleSelectAddress = (item:AddressItem) => {
        dispatch(selectAddress(item))
        Taro.navigateBack(); // 选择后返回上一页
    }

    // 获取地址列表
    const getAddressList = async () => {
        try {
            const { data } = await axios.get('http://localhost:3000/getAddress')
            if (data.code === 200) {
                setAddressList(data.address)
            } else {
                Taro.showToast({
                    title: '获取地址列表失败',
                    icon: 'none'
                })
            }
        } catch (error) {
            Taro.showToast({
                title: '获取地址列表失败',
                icon: 'none'
            })
        }
    }

    useEffect(() => {
        getAddressList()
    }, [])

    return (
        <View className="address-page">
            <NavBar
                title="收货地址"
                leftText="返回"
                leftArrow={<ArrowLeft />}
                onClickLeft={() => Taro.navigateBack()}
            />

            {addressList.map(item => (
                <Cell.Group key={item._id}>
                    <Cell
                        title={<div>{item.username} {item.phone}</div>}
                        label={`${item.address.join(' ')} ${item.dAddress}`}
                        isLink
                        onClick={() => handleSelectAddress(item)}
                    />
                </Cell.Group>
            ))}

            <View className="fixed-bottom">
                <Button
                    block
                    type="danger"
                    onClick={() => Taro.navigateTo({ url: '/user/pages/address/edit/index' })}
                >
                    新增收货地址
                </Button>
            </View>
        </View>
    )
}

const Address = () => {
    return (
        <Provider store={store}>
            <AddressContent />
        </Provider>
    )
}

export default Address
